package com.shiro.controller;

import com.shiro.service.UserService;
import org.apache.catalina.User;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
public class MyController {


    @Resource
    UserService userService;

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","我来了");
        return "index";
    }


    @RequestMapping("/user/add")
    public String useradd(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String userupdate(){
        return "user/update";
    }

    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }


    @RequestMapping("/noauth")
    @ResponseBody
    public String noauth(){
        return "未授权,没有权限访问此页面！";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录信息  UsernamePasswordToken使用以后全局作用(数据存储)
        UsernamePasswordToken Token = new UsernamePasswordToken(username,password);
        try {
            subject.login(Token);//执行了登录方法 ， 如果没有异常就OK了
            return "index";
        }catch (UnknownAccountException e){//用户名不存在异常
            model.addAttribute("msg","用户名错误！");
            return "login";
        }catch (IncorrectCredentialsException e){//密码不存在异常
            model.addAttribute("msg","密码错误！");
            return "login";
        }
    }



}
